import paramiko,multiprocessing


# ssh客户端
def ssh_client(ip,username,passwd,command,port):
    # 建立一个ssh客户端对象
    ssh = paramiko.SSHClient()
    # 将信任的主机自动加到host_allow列表，需放在connect方法前
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy)
    # 连接服务器
    ssh.connect(hostname=ip,port=port,username=username,password=passwd)
    # 结果返回到stdout中，错误放在stderr中
    stdin,stdout,stderr = ssh.exec_command(command)
    # 解码
    print(stdout.read().decode())

    # 关闭连接
    # ssh.close()


# sftp客户端
def sftp_client(ip,username,passwd,local_path,remote_path,port):
    # 指定ip和端口建立连接
    trans = paramiko.Transport((ip,port))
    trans.connect(username=username,password=passwd)
    # 实例化一个sftp对象，指定连接的通道
    sftp = paramiko.SFTPClient.from_transport(trans)
    # 下载文件
    sftp.put(localpath=local_path,remotepath=remote_path)
    print("传输成功")
    # # 关闭连接
    # trans.close()


def return_msg(ip, username, passwd, local_path, remote_path, command,port):
    sftp_client(ip,username,passwd,local_path,remote_path,port)
    ssh_client(ip, username, passwd, command, port)


if __name__ == "__main__":
    ip_list = ['192.168.99.129','192.168.99.130']
    username = 'root'
    password = '123456'
    local_path = r"C:\Users\Administrator\PycharmProjects\pythonProject\1909059114江旭川sendmail.py"
    remote_path = '/watch_etc1.py'
    cmd = 'python3 /watch_etc1.py'
    port = 22
    for ip in ip_list:
        proc = multiprocessing.Process(target=return_msg,args=(ip,username,password,local_path,remote_path,cmd,port))
        proc.start()

